import 'package:flutter/material.dart';
import 'package:hi_net/navigator/hi_navigator.dart';
import 'package:hi_net/util/string_util.dart';
import 'package:hi_net/util/toast.dart';
import 'package:hi_net/widget/appbar.dart';
import 'package:hi_net/widget/login_button.dart';
import 'package:hi_net/widget/login_effect.dart';
import 'package:hi_net/widget/login_input.dart';

import '../http/core/hi_net_error.dart';
import '../http/dio/login_dao.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  var protect = false;
  bool loginEnable = false;
  String? userName;
  String? password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar("登录", "注册", () => HiNavigator.getInstance.onJumpTo(RouteStatus.register)),
      body: Container(
        child: ListView(
          children: [
            LoginEffect(protect: protect),
            LoginInput("用户名", "请输入用户名", onChanged: (value) {
              userName = value;
              checkInput();
            }),
            LoginInput("密码", "请输入密码", obscureText: true, onChanged: (value) {
              password = value;
              checkInput();
            }, focusChanged: (focus) {
              setState(() {
                protect = focus;
              });
            }),
            Padding(padding: const EdgeInsets.all(20), child: LoginButton("登录", enable: loginEnable, onPressed: send))
          ],
        ),
      ),
    );
  }

  void checkInput() {
    setState(() {
      loginEnable = isNotEmpty(userName) && isNotEmpty(password);
    });
  }

  void send() async {
    try {
      var result = await LoginDao.login(userName!, password!);
      print("loginRequest result: $result");
      if (result['code'] == 0) {
        print('登录成功');
        showToast('登录成功');
      } else {
        print(result['msg']);
        showWarnToast(result['msg']);
      }
      HiNavigator.getInstance.onJumpTo(RouteStatus.main);
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast("登录失败：${e.message}");
    } on NeedLogin catch (e) {
      print(e);
      showWarnToast("登录失败：${e.message}");
    } on HiNetError catch (e) {
      print(e);
      showWarnToast("登录失败：${e.message}");
    }
  }
}
